<template>
    <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">
        <el-row :gutter="20">
            <el-col :span="6">
                <span>项目编号：{{ projectInfo.projectCode }}</span>
            </el-col>
            <el-col :span="6">
                <span>项目名称：{{ projectInfo.projectName }}</span>
            </el-col>
            <el-col :span="6">
                <span>采购类别：{{ categoryName }}</span>
            </el-col>
            <el-col :span="6">
                <span>采购类别：{{ projectInfo.budget }}元</span>
            </el-col>
            <el-col :span="24">
                <div style="margin-top: 20px">
                    <span>归档文件：</span>
                    <el-table :data="projectFileTable" style="width: 100%;margin-top: 10px" class="table" border>
                        <el-table-column prop="fileCategory" label="文件类别"></el-table-column>
                        <el-table-column prop="fileName" label="文件名"></el-table-column>
                        <el-table-column prop="fileArchiveTime" label="归档时间"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" style="margin-left: 20px" @click="downloadFile(scope.row.filePath,scope.row.fileCategory,scope.row.fileName)">下载</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- "打包下载" (Pack & Download) button -->
                    <el-button size="small" class="packDownload" type="primary" @click="packAndDownload">打包下载</el-button>&emsp;<span>(打包成一个压缩包)</span>
                </div>
            </el-col>
            <el-col :span="12">
                <div style="margin-top: 20px">
                    <el-col :span="12">
                        <span>提交状态：{{ projectInfo.archiveSubmitStatus }}</span>
                    </el-col>
                    <el-col :span="12">
                        <span>提交时间：{{ projectInfo.archiveSubmitTime }}</span>
                    </el-col>
                    <el-col :span="12">
                        <span v-if="status === ''">审批状态：{{ projectInfo.archiveApproveStatus }}</span>
                        <span v-else>审批状态：{{ status }}</span>
                    </el-col>
                    <el-col :span="12">
                        <span>审批时间：{{ projectInfo.archiveApproveTime }}</span>
                    </el-col>
                    <el-col :span="24">
                        <!-- 审批意见 -->
                        <span >审批意见:</span>
                        <el-input v-model="projectAllInfo.archiveApproveSuggestion" type="textarea" rows="4" placeholder="请输入审批意见"></el-input>
                    </el-col>
                </div>
                <div style="margin-top: 10px">
                    <el-col :span="24" style="margin-top: 10px">
                        <el-col :span="8" v-if="projectInfo.archiveApproveStatus !== '审批通过'">
                            <el-button size="small" type="primary" @click="ChangeStatusPass" :disabled="buttonStatus">审批通过</el-button>
                        </el-col>
                        <el-col :span="8" >
                            <el-button size="small" type="warning" @click="ChangeStatusOut" :disabled="buttonStatus">退回</el-button>
                        </el-col>
                        <el-col :span="8">
                            <el-button size="small" type="primary" @click="goBack">返回</el-button>
                        </el-col>
                    </el-col>
                </div>
            </el-col>
        </el-row>


    </div>
</template>

<script>
//npm install jszip file-saver  引入jszip
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import request from "@/utils/request";
import {archiveApproved, archiveCancel, selectAllArchiveApprovalManger} from "@/api/archiveApproval/archiveApproval";
import {changeArchiveApproveState, ChangeStatus} from "@/api/shoppingManage/archiveApproval";
import {downloadZip, selectAllArchiveManger} from "@/api/archive/archive";


export default {
    props: {
        projectInfo:{
            type: Object,
            default() {
                return {}
            }
        },
        // 修改状态后更新列表信息
        queryClick:{
            type: Function
        },
        // 关闭窗口的方法
        closeDialog: {
            type: Function
        },
        // 传过来的项目涉及文件
        projectFileTable:{
          type: []
        },
        // c采购类别
        categoryName:{
            type:String
        },
        request: true
    },
    data() {
        return {
            loading: true,
            failureDialogVisible: false,
            archiveApproveSuggestion: '',
            projectAllInfo: {}, // 用来保存传过来的用户信息
            status: "",
            buttonStatus: false,
        };
    },
    // 侦听
    watch:{
        projectInfo:{
            handler(newV) {
                this.projectAllInfo = JSON.parse(JSON.stringify(newV));
            },
            deep: true
        }
    },


  methods: {

    //下载
    async downloadFile(filePath,fileCategory,fileName){
      if (!filePath) {
        this.$message.error("文件路径不存在，无法下载。");
        return;
      }
      let data={
        'projectId':this.projectInfo.projectId,
        'filePath':filePath,
        'fileCategory':fileCategory,
        'fileName':fileName
      }
      console.log(data)
      let res=await request(
          {
            url: "/archive/downloadfile",
            method: "post",
            responseType: 'blob',
            data:data,
          }
      )

      let blob = new Blob([res.data], {type: 'application/octet-stream'})
      // 创建一个临时的URL，用于下载文件
      let url = window.URL.createObjectURL(blob)
      // 创建一个a标签，指定下载链接和文件名
      let link = document.createElement('a')
      link.href = url
      link.download =filePath // 这里可以根据实际情况指定文件名和扩展名
      // 触发a标签的点击事件，开始下载文件
      link.click()
      // 释放URL资源
      window.URL.revokeObjectURL(url)
    },


    //打包下载
    async packAndDownload() {
      console.log(this.projectInfo)
      let theData ={ projectId: this.projectInfo.projectId }
      console.log("=========theData===========" + JSON.stringify(theData))
      try {
        this.loading = true;
        this.$message({
          type: 'info',
          message: '正在打包下载中...'
        });
        let response = await downloadZip(theData);
        if(response.headers['content-type']!=='application/octet-stream'){
          this.$message({
            message:'数据已发生变化，请重试'
          })
          this.loading=false;
          return;
        }
        // 问题，response.data为空，new blob对象为空
        let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
        // 创建一个临时的URL，用于下载文件
        let url = window.URL.createObjectURL(blob)
        // 创建一个a标签，指定下载链接和文件名
        let link = document.createElement('a')
        link.href = url
        link.download ="审批文件.zip" // 这里可以根据实际情况指定文件名和扩展名
        // 触发a标签的点击事件，开始下载文件
        link.click()
        // 释放URL资源
        window.URL.revokeObjectURL(url)
        this.loading = false;
      } catch (error) {
        this.$message.error("存在文件路径为空，下载失败");
        this.loading = false;
      }
    },


        //审批通过
        async ChangeStatusPass() {
            this.$loading({
                fullscreen: true,
            });
            try {
                let theData = {
                    projectId: this.projectInfo.projectId,
                    suggestion: this.projectAllInfo.archiveApproveSuggestion,
                    status: "审批通过"
                }
                debugger
                let res = await changeArchiveApproveState(theData)
                if (res.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '通过成功!'
                    });
                    this.queryClick()
                    this.status = "审批通过";
                    this.buttonStatus = true;
                } else {
                    this.$message.error(res.data.msg)
                }
            } catch (e) {
                this.$message.error("出错")
            } finally {
                this.$loading().close();
            }
        },

        //审批退回
        async ChangeStatusOut() {
            this.$loading({
                fullscreen: true,
            });
            // 发出事件以更新index中的审批状态
            try {
                let theData = {
                    projectId: this.projectInfo.projectId,
                    suggestion: this.projectAllInfo.archiveApproveSuggestion,
                    status: "退回"
                }
                let res = await changeArchiveApproveState(theData)
                if (res.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '已退回!'
                    });
                    this.queryClick()
                    this.status = "退回";
                    this.buttonStatus = true;
                } else {
                    this.$message.error(res.data.msg)
                }
            } catch (e) {
                this.$message.error(e.messages)
            } finally {
                this.$loading().close();
            }
        },


        //返回archive
        goBack() {
            this.buttonStatus = false;
            this.status = "";
            this.canBeArchived = "";
            this.projectFileTable = [];
            this.failureDialogVisible = false;
            this.archiveApproveSuggestion = "";
            this.projectAllInfo = {};
            this.closeDialog()
        },

    },

};
</script>

<style>

.showCurrentStatus {
    margin-top: 30px;
}

.packDownload {
    margin-top: 30px;
}

.centered-buttons {
    text-align: center;
    margin-top: 20px;
}

.submit-button {
    margin-right: 20px;
}

.back-button {
    margin-top: 10px
}
</style>

